package cn.edu.hit.core.message;

import com.fasterxml.jackson.databind.JavaType;
import cn.edu.hit.core.Document;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;

/**
 * 对随机的数据进行生成
 */
@Deprecated
public final class WaveAdapter extends MessageAdapterHelper {
    @Override
    public boolean accept(String type) {
        return "Wave".equalsIgnoreCase(type);
    }

    private static final Random random = new Random();
    private static JavaType doubleListType = mapper.getTypeFactory().constructParametricType(List.class, Double.TYPE);

    @Override
    public Stream<Map> service(Long timestamp) {
        return configureMap.entrySet().parallelStream().map(entry -> {
            Document result = new Document();
            String id = entry.getKey();
            Document configure = (Document) entry.getValue();

            result.put(PORT_ID, id);
            result.put("portName", configure.getString("portName"));

            String argString = configure.getString(DATA_SOURCE_ARGS);
            List<Double> value;
            try {
                value = mapper.readValue(argString, doubleListType);
                double avg = getDefault(value, 0, 10);
                double val = avg;
                for (int i = 1; i < value.size(); i += 3) {
                    double T = getDefault(value, i, 1);
                    T = T < 0.0000001 ? 1 : T;
                    double fudu = getDefault(value, i + 1, 2);
                    double fi = getDefault(value, i + 2, 0);
                    val += fudu * Math.sin(Math.PI * (2 * (timestamp % 1000 / 1000.0) / T) + fi);
                }
                result.put(VALUE, Collections.singletonList(val));
            } catch (Exception e) {
                e.printStackTrace();
                double val = 10 + 2 * Math.sin(2 * Math.PI * (timestamp % 1000 / 1000.0));
                result.put(VALUE, Collections.singletonList(val));
            }

            result.put(TIMESTAMP, timestamp);
            return result;
        });
    }

    private static double getDefault(List<Double> list, int index, double defaultVal) {
        if (list == null || index < 0 || index >= list.size()) {
            return defaultVal;
        }
        return list.get(index);
    }
}
